//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.jeecgframework.poi.excel.imports;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.DateUtils;
import org.jeecgframework.poi.excel.entity.params.ExcelImportEntity;
import org.jeecgframework.poi.excel.entity.sax.SaxReadCellEntity;
import org.jeecgframework.poi.exception.excel.ExcelImportException;
import org.jeecgframework.poi.exception.excel.enums.ExcelImportEnum;
import org.jeecgframework.poi.handler.inter.IExcelDataHandler;
import org.jeecgframework.poi.util.ExcelUtil;
import org.jeecgframework.poi.util.PoiPublicUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class CellValueServer {
    private static final Logger LOGGER = LoggerFactory.getLogger(CellValueServer.class);
    private List<String> hanlderList = null;

    public CellValueServer() {
    }

    private Object getCellValue(String xclass, Cell cell, ExcelImportEntity entity) {
        if (cell == null) {
            return "";
        } else {
            Object result = null;
            if (!"class java.util.Date".equals(xclass) && !"class java.sql.Time".equals(xclass)) {
                if (0 == cell.getCellType()) {
                    result = cell.getNumericCellValue();
                } else if (4 == cell.getCellType()) {
                    result = cell.getBooleanCellValue();
                } else {
                    result = cell.getStringCellValue().trim();
                }
            } else {
                if (0 == cell.getCellType()) {
                    result = cell.getDateCellValue();
                } else {
                    result = this.getTime(cell.getStringCellValue().trim());
                    if (result == null){
                        cell.setCellType(1);
                        result = this.getDateData(entity, cell.getStringCellValue().trim());
                    }
                }

                if ("class java.sql.Time".equals(xclass)) {
                    result = new Time(((Date) result).getTime());
                }
            }

            return result;
        }
    }

    //判断 并转换时间格式 ditNumber = 43607.4166666667
    private Date getTime(String ditNumber) {
        if (StringUtils.isBlank(ditNumber)){
            return null;
        }
        //如果不是数字
        if(!isNumeric(ditNumber)){
            return null;
        }
        //如果是数字 小于0则 返回
        BigDecimal bd = new BigDecimal(ditNumber);
        int days = bd.intValue();//天数
        int mills = (int) Math.round(bd.subtract(new BigDecimal(days)).doubleValue() * 24 * 3600);

        //获取时间
        Calendar c = Calendar.getInstance();
        c.set(1900, 0, 1);
        c.add(Calendar.DATE, days - 2);
        int hour = mills / 3600;
        int minute = (mills - hour * 3600) / 60;
        int second = mills - hour * 3600 - minute * 60;
        c.set(Calendar.HOUR_OF_DAY, hour);
        c.set(Calendar.MINUTE, minute);
        c.set(Calendar.SECOND, second);

        return c.getTime();//Date
    }

    //校验是否数据含小数点
    private static boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]+\\.*[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if(!isNum.matches()){
            return false;
        }
        return true;
    }

    private Date getDateData(ExcelImportEntity entity, String value) {
        if (StringUtils.isNotEmpty(entity.getFormat()) && StringUtils.isNotEmpty(value)) {
            SimpleDateFormat format = new SimpleDateFormat(entity.getFormat());
            try {
                return format.parse(value);
            } catch (ParseException var5) {
                Date date = DateUtils.parseDate(value);
                if (date != null){
                    return date;
                }
                String message = String.format("时间格式化失败,格式化:%s,值:%s", entity.getFormat(), value);
                LOGGER.error(message);
                throw new ExcelImportException(ExcelImportEnum.GET_VALUE_ERROR.getMsg() + "：" + message);
            }
        } else {
            return DateUtils.parseDate(value);
        }
    }

    public Object getValue(IExcelDataHandler dataHanlder, Object object, Cell cell, Map<String, ExcelImportEntity> excelParams, String titleString) throws Exception {
        ExcelImportEntity entity = (ExcelImportEntity) excelParams.get(titleString);
        String xclass = "class java.lang.Object";
        if (!(object instanceof Map)) {
            Method setMethod = entity.getMethods() != null && entity.getMethods().size() > 0 ? (Method) entity.getMethods().get(entity.getMethods().size() - 1) : entity.getMethod();
            Type[] ts = setMethod.getGenericParameterTypes();
            xclass = ts[0].toString();
        }

        Object result = this.getCellValue(xclass, cell, entity);
        if (entity != null) {
            result = this.hanlderSuffix(entity.getSuffix(), result);
            if (entity.isDicCode()){
                result = this.replaceValue(entity.getReplace(), result, entity.isMultiReplace());
            }
        }

        result = this.hanlderValue(dataHanlder, object, result, titleString);
        return this.getValueByType(xclass, result, entity);
    }

    public Object getValue(IExcelDataHandler dataHanlder, Object object, SaxReadCellEntity cellEntity, Map<String, ExcelImportEntity> excelParams, String titleString) {
        ExcelImportEntity entity = (ExcelImportEntity) excelParams.get(titleString);
        Method setMethod = entity.getMethods() != null && entity.getMethods().size() > 0 ? (Method) entity.getMethods().get(entity.getMethods().size() - 1) : entity.getMethod();
        Type[] ts = setMethod.getGenericParameterTypes();
        String xclass = ts[0].toString();
        Object result = cellEntity.getValue();
        result = this.hanlderSuffix(entity.getSuffix(), result);
        if (entity.isDicCode()){
            result = this.replaceValue(entity.getReplace(), result, entity.isMultiReplace());
        }
        result = this.hanlderValue(dataHanlder, object, result, titleString);
        return this.getValueByType(xclass, result, entity);
    }

    private Object hanlderSuffix(String suffix, Object result) {
        if (StringUtils.isNotEmpty(suffix) && result != null && result.toString().endsWith(suffix)) {
            String temp = result.toString();
            return temp.substring(0, temp.length() - suffix.length());
        } else {
            return result;
        }
    }

    private Object getValueByType(String xclass, Object result, ExcelImportEntity entity) {
//        log.info("获取到Excel的value：", result);
        try {
            if (result != null && !"null".equals(String.valueOf(result)) && StringUtils.isNotBlank(String.valueOf(result))) {
                if ("class java.util.Date".equals(xclass)) {
                    return result;
                } else if (!"class java.lang.Boolean".equals(xclass) && !"boolean".equals(xclass)) {
                    if (!"class java.lang.Double".equals(xclass) && !"double".equals(xclass)) {
                        if (!"class java.lang.Long".equals(xclass) && !"long".equals(xclass)) {
                            if (!"class java.lang.Float".equals(xclass) && !"float".equals(xclass)) {
                                if (!"class java.lang.Integer".equals(xclass) && !"int".equals(xclass)) {
                                    if ("class java.math.BigDecimal".equals(xclass)) {
                                        BigDecimal temp = new BigDecimal(String.valueOf(result).trim());
                                        return temp;
                                    } else if ("class java.lang.String".equals(xclass)) {
                                        if (result instanceof String) {
                                            return ExcelUtil.remove0Suffix(result).trim();
                                        } else {
                                            return result instanceof Double ? PoiPublicUtil.doubleToString((Double) result) : ExcelUtil.remove0Suffix(String.valueOf(result));
                                        }
                                    } else {
                                        return result;
                                    }
                                } else {
                                    Integer temp = Integer.valueOf(ExcelUtil.remove0Suffix(String.valueOf(result).trim()));
                                    return temp;
                                }
                            } else {
                                Float temp = Float.valueOf(String.valueOf(result).trim());
                                return temp;
                            }
                        } else {
                            Long temp = Long.valueOf(ExcelUtil.remove0Suffix(String.valueOf(result).trim()));
                            return temp;
                        }
                    } else {
                        Double temp = Double.valueOf(String.valueOf(result).trim());
                        return temp;
                    }
                } else {
                    Boolean temp = Boolean.valueOf(String.valueOf(result).trim());
                    return temp;
                }
            } else {
                return null;
            }
        } catch (Exception var5) {
//            LOGGER.error(var5.getMessage(), var5);
//            throw new ExcelImportException(ExcelImportEnum.GET_VALUE_ERROR);
            String message = String.format("值格式错误或系统不存在%s,值:%s", xclass, result);
            LOGGER.error(message);
            throw new ExcelImportException(ExcelImportEnum.VERIFY_ERROR.getMsg() + "：" + message);
//            return null;
        }
    }

    private Object hanlderValue(IExcelDataHandler dataHanlder, Object object, Object result, String titleString) {
        if (dataHanlder != null && dataHanlder.getNeedHandlerFields() != null && dataHanlder.getNeedHandlerFields().length != 0) {
            if (this.hanlderList == null) {
                this.hanlderList = Arrays.asList(dataHanlder.getNeedHandlerFields());
            }

            return this.hanlderList.contains(titleString) ? dataHanlder.importHandler(object, titleString, result) : result;
        } else {
            return result;
        }
    }

    private Object replaceValue(String[] replace, Object result, boolean multiReplace) {
        if (result == null || StringUtils.isBlank(String.valueOf(result))) {
            return "";
        } else if (replace != null && replace.length > 0) {
            String temp = String.valueOf(result);
            String backValue = "";
            if (temp.indexOf(",") > 0 && multiReplace) {
                String[] multiReplaces = temp.split(CommonConstant.DEFAULT_SEPARATOR);
                String[] var7 = multiReplaces;
                int var8 = multiReplaces.length;

                for (int var9 = 0; var9 < var8; ++var9) {
                    String str = this.replaceSingleValue(replace, var7[var9]);
                    if (StringUtils.isNotBlank(str))
                        backValue = backValue.concat(str + ",");
                }

                if (backValue.length() > 0) {
                    backValue = backValue.substring(0, backValue.length() - 1);
                }
//                if (backValue.equals("")) {
//                    backValue = temp;
//                } else {
//                    backValue = backValue.substring(0, backValue.length() - 1);
//                }
            } else {
                backValue = this.replaceSingleValue(replace, temp);
            }

            return backValue;
        } else {
            return result;
//            return "";
        }
    }

    private String replaceSingleValue(String[] replace, String temp) {
        for (int i = 0; i < replace.length; ++i) {
            String[] tempArr = replace[i].split("_");
            if (temp.equals(tempArr[0]) || temp.equals(tempArr[0].split(";")[0])) {
                return tempArr[1];
            }
        }

        return temp;
//        return "";
    }
}
